//
//  WJOAuthController.m
//  weibo
//
//  Created by 王俊 on 15/12/30.
//  Copyright © 2015年 王俊. All rights reserved.
//


/*
 App Key：1149894125
 App Secret：3b4a2be5d69de033a70c3e3e1ea7815d
 /?code=b2a0edc382122c6587a521654860e102
 */


#import "WJOAuthController.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "WJAccount.h"
#import "NSString+WJStringExt.h"

@interface WJOAuthController ()

@end

@implementation WJOAuthController

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIWebView *webView = [[UIWebView alloc]init];
    webView.frame = self.view.bounds;
    NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=1149894125&redirect_uri=http://"];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:urlString]];
    [webView loadRequest:request];
    webView.delegate = self;
    [self.view addSubview:webView];
    // Do any additional setup after loading the view.
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    //WJLog(@"%@",url);
    NSRange range = [url rangeOfString:@"code="];
    if (range.length != 0 ) {
        int fromIndex = range.location + range.length;
        NSString *code = [url substringFromIndex:fromIndex];
        //WJLog(@"%@",code);
        [self accessTokenWithCode:code];
    }

    return true;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)accessTokenWithCode:(NSString*)code
{
    //  https://api.weibo.com/oauth2/access_token
    AFHTTPSessionManager *mangager = [AFHTTPSessionManager manager];
    mangager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"client_id"] = @"1149894125";
    dict[@"client_secret"] = @"3b4a2be5d69de033a70c3e3e1ea7815d";
    dict[@"grant_type"] = @"authorization_code";
    dict[@"redirect_uri"] = @"http://";
    dict[@"code"] = code;
    [mangager POST:@"https://api.weibo.com/oauth2/access_token" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        /*
         responseObject is: {
         "access_token" = "2.00FUiNsB8zpoPBc0c2528a319UUlkC";//令牌
         "expires_in" = 157679999;//过期时间
         "remind_in" = 157679999;//过期提醒时间
         uid = 1717324241;//用户授权
         }

         */
        //将服务器返回的数据转换为模型
        WJAccount *account = [WJAccount mj_objectWithKeyValues:responseObject];
        //将模型存储到沙盒中
        /*
         NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
         WJLog(@"%@",docPath);
         NSString *accountPath = [docPath stringByAppendingPathComponent:@"account.data"];
         */
        [account save];

        WJLog(@"account is: %@",account);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        WJLog(@"FAIL:%@",error);
    }];
    
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD showWithStatus:@"正在努力加载中"];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
    
}



@end
